<?php
/**
 * Created by 胡祥能 on 2018/4/10.
 *  email：huxiangneng@jiuletech.com
 */

namespace App\Http\Controllers\Admin;


use App\Helpers\Api\ApiResponse;
use App\Models\Sidebar;
use App\Role;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Log;

class UserController extends DefaultController
{
    use ApiResponse;

    public function index(Request $request)
    {
        $perPage = $request->input('perPage')?:10;
        $username = $request->input('username');
        $where = [];
        if (!empty($username)) {
            array_push($where, ['name', '=', $username]);
        }

        $users = User::where($where)->paginate($perPage);
        foreach ($users as &$user) {
            $user->roles = DB::table('role_user')
                ->select('roles.*')
                ->where('role_user.user_id', $user->id)
                ->leftJoin('roles','roles.id','=','role_user.role_id')
                ->get();
        }
        return view('admin.user.index', ['users'=>$users]);
    }

    public function add(Request $request)
    {
        if($request->method() == 'POST'){
            $validator = Validator::make($request->all(), [
                'username' => 'bail|required|max:50',
                'email' => 'bail|required|max:50',
                'pwd' => 'bail|required|max:20',
            ]);

            try {
                DB::beginTransaction();
                $user = new User();
                $user->name = $request->input('username');
                $user->email = $request->input('email');
                $user->password = md5($request->input('pwd'));
                $user->save();

                $roles = $request->input('assign-roles');
                if (is_array($roles) && $roles) {
                    $sql = [];
                    foreach ($roles as $role_id){
                        array_push($sql, ['user_id'=>$user->id, 'role_id'=>$role_id]);
                    }
                    DB::table('role_user')->insert($sql);
                }

                Sidebar::deleteUserSidebarCache();
                DB::commit();
                return $this->successView('');
            } catch (\Exception $exception) {
                Log::info($exception->getMessage() . $exception->getLine());
                DB::rollBack();//出异常，回滚
                return $this->failView('出了一点小问题', '/users');
            }

        }else{
            $roles = Role::all();
            return view('admin.user.add', ['roles'=>$roles]);
        }
    }

    public function updateStatus(Request $request){
        $id = $request->input('id');
        $status = $request->input('status');
        if(empty($id)){
            return $this->json(1001);
        }

        $res = User::where('id', $id)->update([
            'status'=>$status
        ]);
        if($res){
            return $this->json(200);
        }else{
            return $this->json(1002);
        }
    }

    public function update(Request $request){
        if($request->method() == "GET"){
            $id = $request->input('id');
            if(empty($id)){
                return view('admin.404');
            }

            $user = User::find($id);
            $roles = Role::all();
            $userRoles = $user->roles()->get()->toArray();
            $assign_ids = array_column($userRoles, 'id');
            foreach ($roles as &$val){
                $val->selected = (in_array($val->id, $assign_ids))?true:false;
            }

            return view('admin.user.update', ['user'=>$user, 'roles'=>$roles]);
        }else{
            $validator = Validator::make($request->all(), [
                'username' => 'bail|required|max:50',
                'email' => 'bail|required|max:50',
            ]);

            try {
                DB::beginTransaction();

                $id = $request->input('id');
                $user = User::find($id);
                $user->name = $request->input('username');
                $user->email = $request->input('email');
                $res = $user->save();

                $userRoles = $user->roles()->get()->toArray();
                $userRolesIdArr = array_column($userRoles, 'id');
                $roles = $request->input('roles-assign')?:[];
                $diff1 = array_diff($userRolesIdArr, $roles);//需要删除的角色id
                $diff2 = array_diff($roles, $userRolesIdArr);//需要增加的角色id

                if($diff1){
                    foreach ($diff1 as $v){
                        DB::table('role_user')->where('user_id', $id)->where('role_id', (int)$v)->delete();
                    }
                }

                if($diff2){
                    foreach ($diff2 as $item){
                        DB::table('role_user')->insert([
                            'user_id'=> $id,
                            'role_id'=> (int)$item
                        ]);
                    }
                }

                $user_cache = $request->session()->get(User::SESSION_KEY);
                if(($diff1 || $diff2)&& $user_cache['id'] == $id){//如果当前用户的，角色分配发生变化
                    $user_cache['roles'] = $user->roles()->get()->toArray();
                    $request->session()->put(User::SESSION_KEY, $user_cache);

                    Sidebar::deleteUserSidebarCache();
                }

                DB::commit();
                if($res){
                    return $this->successView('', '/users');
                }else{
                    return $this->failView('', '/users');
                }

            } catch (\Exception $exception) {
                Log::info($exception->getMessage() . $exception->getLine());
                DB::rollBack();//出异常，回滚
                return $this->failView('出了一点小问题', '/users');
            }
        }
    }
}